<!--
 * @Author: yaojian66 1327629137@qq.com
 * @Date: 2022-07-05 14:01:39
 * @LastEditors: yaojian66 1327629137@qq.com
 * @LastEditTime: 2022-07-05 14:05:25
 * @FilePath: \geyao\第一百零六题 监听对象.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>监听对象</title>
</head>
<style>
  ul {
      list-style: none;
  }
</style>
<body>
  <ul></ul>
  <script>
    var ul = document.querySelector('ul');
    var person = {
      sex: '男',
      age: '25',
      name: '王大锤',
      height: 28,
      weight: 32
    };
    const _render = element => {
      var str = `<li>姓名：<span>${person.name}</span></li>
                   <li>性别：<span>${person.sex}</span></li>
                   <li>年龄：<span>${person.age}</span></li>
                   <li>身高：<span>${person.height}</span></li>
                   <li>体重：<span>${person.weight}</span></li>`
      element.innerHTML = str;
    }
    _render(ul);
    // 补全代码
    function Observe(target) {
      if (typeof target !== 'object' || target == null) {
        return target
      }
      for (var key in target) {
        defineReactive(target, key, target[key])
      }
    }

    function defineReactive(target, key, value) {
      Object.defineProperty(target, key, {
        get: function () {
          return value
        },
        set: function (newVal) {
          if (newVal !== value) {
            value = newVal
            _render(ul)
          }

        }

      })
    }
    Observe(person)
  </script>
</body>

</html>